<template>
  <!--采单打印-->
  <div class="mod-config">
    <el-row style="padding: 10px;">
      <div style="width: 1020px;margin: auto;">
        <el-button class="filter-item" plain style="margin-left: 10px;" type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
        <el-button type="primary" plain @click="handleWindowPrint( '#demo', '采购单' )">浏览器方式下载</el-button>
      </div>
    </el-row>
    <div style="width: 100%">
      <div id="demo">
        <h2><center><b>采 购 单</b></center></h2>
        <el-table :data="tableData" :span-method="arraySpanMethod" :show-header="false" style="width: 100%" border >
          <el-table-column prop="one" width="170">
            <template slot-scope="scope">
              <div style="text-align: right;color: black;padding: 10px 10px"><span>{{scope.row.one}}</span></div>
            </template>
          </el-table-column>
          <el-table-column prop="oneValue">
            <template slot-scope="scope">
              <div v-if="scope.row.oneType === 1" style="text-align: left;color: black;font-weight: bold;padding: 10px 0"><span>{{scope.row.oneValue}}</span></div>
              <div v-if="scope.row.oneType === 2" style="padding: 20px">
                <el-table :data="detailList"  style="width: 100%" :header-cell-style="tableHeaderStyle" :row-style="tableRowStyle"
                          border show-summary>
                  <el-table-column prop="productByProductId.productName" label="产品名" >
                  </el-table-column>
                  <el-table-column prop="productByProductId.productModel" label="型号" >
                  </el-table-column>
                  <el-table-column prop="productDetailCount" label="数量" >
                  </el-table-column>
                  <el-table-column prop="productDetailIntoNum" label="已入库" >
                  </el-table-column>
                  <el-table-column prop="productDetailOutNum" label="未入库" >
                  </el-table-column>
                  <el-table-column prop="productDetailPrice" label="单价" >
                    <template slot-scope="scope">
                      ￥{{scope.row.productDetailPrice}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="productDetailMoney" label="金额" >
                    <template slot-scope="scope">
                      ￥{{ (scope.row.productDetailMoney = scope.row.productDetailPrice *scope.row.productDetailCount)}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="productDetailRemarks" label="备注" >
                  </el-table-column>
                </el-table>
                <div style="padding: 10px 0 0 0">总计（大写金额）：{{purchase.purchaseAmount |ToString}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="two">
            <template slot-scope="scope">
              <div style="text-align: right;color: black;padding: 10px 10px"><span>{{scope.row.two}}</span></div>
            </template>
          </el-table-column>
          <el-table-column prop="twoValue">
            <template slot-scope="scope">
              <div style="text-align: left;color: black;font-weight: bold;padding: 10px 0"><span>{{scope.row.twoValue}}</span></div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
  import htmlToPdf from '../assets/htmlToPdf'
  const libraryOption = [{id: 0, name: '家庭原因'}, {id: 1, name: '个人发展'}, {id: 2, name: '薪资福利'},
    {id: 3, name: '工作环境'}, {id: 4, name: '工作时间'}, {id: 5, name: '身体健康'}]
  const calendarTypeKeyValue = libraryOption.reduce((acc, cur) => {
    acc[cur.id] = cur.name
    return acc
  }, {})
  export default {
    name: 'Test',
    data () {
      // 和导出pdf没关系
      return {
        nowtime:'',//日期
        emp:{},
        contact:{
          contactPhone:'',
          contactWechat:'',
          contactAddress:''
        },
        purchase: {
          purchaseId: 0,
          purchaseTheme: '',
          purchaseNo: '',
          purchaseDate: '',
          purchasePredictDate: '',
          purchaseStatus: '',
          purchaseSort: '',
          purchaseAmount: '',
          purchaseNote: '',
          purchaseContactName: '',
          purchaseBill: 0,
          purchasePaid: 0,
          purchaseAppStatus: 0,
          purchaseReturn: 1,
          customerByCustomerId: {},
          employeeByEmpId: {},
          customerByConCustomerId:null,
          contractByContractId:null,
          employeeByAppEmpId:null,
          warehouseByWarehouseId:{}
        },
        detailList: [],//明细集合
        tableData:[{
          one:'采购单号:',
          oneValue:'',
          oneType:1,
          two:'采购日期:',
          twoValue:'',
        }, {
          one:'采购主题:',
          oneValue:'',
          oneType:1,
          two:'采购单ID:',
          twoValue:'',
        },{
          one:'供应商:',
          oneValue:'',
          oneType:1,
          two:'经手人',
          twoValue:'',
        },{
          one:'联系人:',
          oneValue:'',
          oneType:1,
          two:'分类',
          twoValue:'',
        },{
          one:'电话:',
          oneValue:'',
          oneType:1,
          two:'仓库',
          twoValue:'',
        },{
          one:'微信:',
          oneValue:'',
          oneType:1,
          two:'采购金额',
          twoValue:'',
        },{
          one:'地址:',
          oneValue:'',
          oneType:1,
          two:'已付金额',
          twoValue:'',
        },{
          one:'采购明细:',
          oneValue:'',
          oneType:2,
          two:'',
          twoValue:'',
        },{
          one:'备注:',
          oneValue:'',
          oneType:1,
          two:'',
          twoValue:'',
        }],
        lxOptions: [{
          value: 1,
          label: '大宗采购'
        }, {
          value: 2,
          label: '零星采购'
        }],
        ztsOptions: [{
          value: 1,
          label: '1新采购'
        }, {
          value: 2,
          label: '2生成入库单'
        }, {
          value: 3,
          label: '3部分入库'
        }, {
          value: 4,
          label: '4入库完成'
        }],
      }
    },
    methods: {
      // 查询当前员工
      loginEmp() {
        this.$axios.get('http://localhost:8088/emp')
          .then(v => {
            this.emp = v.data
            this.compute()
          })
          .catch(function (v) {
          })
      },
      //获取今天日期
      getNowTime() {
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth(); //得到月份
        var date = now.getDate(); //得到日期
        month = month + 1;
        month = month.toString().padStart(2, "0");
        date = date.toString().padStart(2, "0");
        var defaultDate = `${year}-${month}-${date}`;
        this.nowtime=defaultDate;
      },
      // 查询采购
      findPurchase () {
        let purId = this.$route.query.purId
        this.$axios.get('http://localhost:8088/pur-id', {
          params: {
            purId : purId
          }
        })
          .then(v => {
            this.purchase = v.data
            if (v.data.purchaseContactName !== null && v.data.purchaseContactName !== ''){
              this.findContact(v.data.purchaseContactName)
            }
            this.loginEmp()
          })
          .catch(function (v) {})
      },
      // 查询详单集合
      findDetailList(){
        let purId = this.$route.query.purId
        this.$axios.get('http://localhost:8088/pur-detail-list', {
          params:{
            purId : purId
          }
        })
          .then(v => {
            this.detailList = v.data
          })
          .catch(function (v) {})
      },
      // 查询联系人
      findContact(val){
        this.$axios.get('http://localhost:8088/contact-buy-name', {
          params:{
            contactName : val
          }
        })
          .then(v => {
            this.contact = v.data[0]
            console.log(this.contact)
          })
          .catch(function (v) {})
      },
      // 赋值
      compute(){
        for(let i=0;i<this.tableData.length;i++) {
          if (i === 0){
            this.tableData[0].oneValue = this.purchase.purchaseNo
            this.tableData[0].twoValue = this.purchase.purchaseDate
          }else if(i === 1){
            this.tableData[1].oneValue = this.purchase.purchaseTheme
            this.tableData[1].twoValue = this.purchase.purchaseId
          }else if(i === 2){
            this.tableData[2].oneValue = this.purchase.customerByCustomerId.customerName
            this.tableData[2].twoValue = this.purchase.employeeByEmpId.empName
          }else if(i === 3){
            this.tableData[3].oneValue = this.purchase.purchaseContactName
            if (this.purchase.purchaseSort !== null){
              this.tableData[3].twoValue = this.lxOptions[this.purchase.purchaseSort - 1].label
            }
          }else if(i === 4){
            this.tableData[4].oneValue = this.contact.contactPhone
            this.tableData[4].twoValue = this.purchase.warehouseByWarehouseId.warehouseName
          }else if(i === 5){
            this.tableData[5].oneValue = this.contact.contactWechat
            this.tableData[5].twoValue = '￥' + this.purchase.purchaseAmount
          }else if(i === 6){
            this.tableData[6].oneValue = this.contact.contactAddress
            this.tableData[6].twoValue = '￥' + this.purchase.purchasePaid
          }else if(i === 8){
            this.tableData[8].oneValue = this.purchase.purchaseNote
          }
        }
      },
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if(rowIndex === 7){
          if (columnIndex === 1) {
            return [1, 3];
          }
        }else if (rowIndex === 8) {
          if (columnIndex === 1) {
            return [1, 3];
          }
        }
      },
      handleWindowPrint (ele, fileName) {
        document.body.innerHTML = document.querySelector(ele).outerHTML
        // 转异步 等待dom元素渲染（样式）完毕在打印
        setTimeout(() => {
          // 打印
          window.print()
          // 刷新页面
          window.location.reload()
        }, 20)
      },
      goBack () {
        this.$router.go(-1)
      },
      tableHeaderStyle(){
        return "text-align:left;color:black"
      },
      tableRowStyle(){
        return 'padding: 10px 0;color:black;'
      }
    },
    created () {
      this.findPurchase()
      this.findDetailList()
      this.getNowTime();
    },
    filters: {
      typeFilter (type) {
        return calendarTypeKeyValue[type]
      },
      ToString(n) {
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)){
          return "数据非法";  //判断数据是否大于0
        }
        var unit = "千百拾亿千百拾万千百拾元角分", str = "";
        n += "00";
        var indexpoint = n.indexOf('.');  // 如果是小数，截取小数点前面的位数
        if (indexpoint >= 0){
          n = n.substring(0, indexpoint) + n.substr(indexpoint+1, 2);   // 若为小数，截取需要使用的unit单位
        }
        unit = unit.substr(unit.length - n.length);  // 若为整数，截取需要使用的unit单位
        for (var i=0; i < n.length; i++){
          str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);  //遍历转化为大写的数字
        }
        return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整"); // 替换掉数字里面的零字符，得到结果
      },
    },
  }
</script>

<style scoped>
  #demo {
    background-color: #fff;
    width: 1000px;
    margin: auto;
    padding: 40px;
    box-sizing: border-box;
  }

</style>
